package com.timing.feedback.auth;


import com.timing.feedback.config.JwtTokenDao;
import com.timing.feedback.entity.UserPO;
import com.timing.feedback.utils.WriteJsonUtil;
import com.timing.feedback.vo.ResultVO;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录成功操作
 * @author cwh
 */
@Component
public class WebAuthenticationSuccessHandler  implements AuthenticationSuccessHandler {

    @Resource
    private JwtTokenDao jwtTokenDao;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        //获取当前的登录用户
        Object principal = authentication.getPrincipal();
        UserPO user = null;
        ResultVO result=ResultVO.error();
        if(principal instanceof UserDetails){
            user = (UserPO)principal;
            Map<String,Object> map = new HashMap<>(2);
            map.put("message","登录成功");
            map.put("token", jwtTokenDao.generateToken(user));
            //装入token
            result= ResultVO.ok().data(map);
        }
        WriteJsonUtil.writeJson(request, response, result);
    }
}
